<template>
  <div class="studentAdmin">
    <el-button
      type="primary"
      style="margin-bottom: 8px"
      size="default"
      @click="openAddStudentDialog"
      >新增学生
    </el-button>
    <el-drawer v-model="drawer" title="新增学生" :with-header="false">
      <div class="drawer-content">
        <el-input v-model="newStudent.name" placeholder="请输入名字" class="drawer-input" />
        <el-input v-model="newStudent.phone" placeholder="请输入手机号" class="drawer-input" />
        <el-select v-model="newStudent.gender" placeholder="请选择性别" class="drawer-input">
          <el-option label="男生" :value="0" />
          <el-option label="女生" :value="1" />
        </el-select>
        <el-button type="primary" @click="addStudent">提交</el-button>
      </div>
    </el-drawer>
    <el-card>
      <div class="search-bar">
        <el-input v-model="searchValue.name" size="default" placeholder="请输入名字" />
        <el-select v-model="searchValue.absentStatus" placeholder="请选择在校状态">
          <el-option label="全部" :value="''" />
          <el-option label="在校" :value="0" />
          <el-option label="请假" :value="1" />
        </el-select>
        <el-input v-model="searchValue.role" size="default" placeholder="请输入身份" />
        <el-select v-model="searchValue.gender" placeholder="请选择性别">
          <el-option label="全部" :value="null" />
          <el-option label="男生" :value="0" />
          <el-option label="女生" :value="1" />
        </el-select>
        <el-button type="primary" @click="getStudentList">搜索</el-button>
      </div>
      <el-table :data="absentList" style="width: 100%">
        <el-table-column label="名字" prop="name" />
        <el-table-column label="性别" prop="gender">
          <template #default="scope">
            <el-tag :type="getGenderTagType(scope.row.gender)">
              {{ scope.row.gender === 0 ? '男生' : '女生' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="身份" prop="role" />
        <el-table-column label="手机号" prop="phone" />
        <el-table-column label="操行分" prop="optionScore">
          <template #default="scope">
            <el-tag :type="getOptionScoreTagType(scope.row.optionScore)">
              {{ scope.row.optionScore }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="在校状态" prop="absentStatus">
          <template #default="scope">
            <el-tag :type="getAbsentStatusTagType(scope.row.absentStatus)">
              {{ getAbsentStatusText(scope.row.absentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="right" fixed="right" min-width="150">
          <template #default="scope">
            <el-button size="default" type="primary" plain @click="openDialog(scope.row)">
              编辑
            </el-button>
            <el-button
              size="default"
              type="warning"
              plain
              @click="(getDutyVO(scope.row.id), (dutyDialogVisible = true))"
            >
              值日安排
            </el-button>
            <el-button
              size="default"
              type="info"
              plain
              @click="((dialogVisible1 = true), (stId = scope.row.id), (stName = scope.row.name))"
            >
              选座
            </el-button>
            <el-popconfirm
              title="确定要删除这个学生吗？"
              @confirm="deleteStudent(scope.row.id)"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button size="default" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :total="total"
        :page-size="searchValue.pageSize"
        :current-page="searchValue.current"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        layout=" prev, pager, next"
        :pager-count="7"
      />
    </el-card>
    <student-dialog
      v-model:dialogVisible="dialogVisible"
      :student="selectedStudent || {}"
      @studentUpdated="getStudentList"
    />
    <el-dialog v-model="dialogVisible1" title="在线选座" width="500">
      <SelectSituationView
        :id="stId"
        :name="stName"
        @closeDialog="handleCloseDialog"
      ></SelectSituationView>
    </el-dialog>
    <el-dialog v-model="dutyDialogVisible" title="Tips" width="500">
      <el-form :model="dutyPeople" label-width="80px">
        <el-form-item label="任务名称">
          <el-select v-model="dutyPeople.taskName" placeholder="请选择">
            <el-option label="扫地" :value="'扫地'" />
            <el-option label="倒垃圾" :value="'倒垃圾'" />
            <el-option label="黑板" :value="'黑板'" />
            <el-option label="公区" :value="'公区'" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务时间">
          <el-select v-model="dutyPeople.taskTime" placeholder="请选择">
            <el-option label="上午" :value="'上午'" />
            <el-option label="下午" :value="'下午'" />
          </el-select>
        </el-form-item>
        <el-form-item label="星期几">
          <el-radio-group v-model="dutyPeople.day">
            <el-radio :value="1">星期一</el-radio>
            <el-radio :value="2">星期二</el-radio>
            <el-radio :value="3">星期三</el-radio>
            <el-radio :value="4">星期四</el-radio>
            <el-radio :value="5">星期五</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dutyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="(updateDuty(), (dutyDialogVisible = false))"
            >确认</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'
import type { duty, StudentInfo } from '@/types/StudentType.ts'
import StudentDialog from '@/views/student/components/StudentDialog.vue'
import SelectSituationView from '@/views/student/components/SelectSituationView.vue'
import { ElMessage } from 'element-plus'

const drawer = ref(false)
const dialogVisible = ref(false)
const dutyDialogVisible = ref(false)
const selectedStudent = ref()
const absentList = ref<Array<StudentInfo>>([])
const total = ref<number>(0)
const stId = ref()
const stName = ref()
const searchValue = ref({
  pageSize: 10,
  current: 1,
  name: '',
  absentStatus: null,
  role: '',
  gender: null,
})
const dutyPeople = ref({
  taskName: '',
  taskTime: '',
  name: '',
  day: 0, // 默认值为星期一
})
const newStudent = ref({
  name: '',
  phone: '',
  gender: null,
})
const dialogVisible1 = ref(false)
const handleCloseDialog = (shouldClose: boolean) => {
  if (!shouldClose) {
    dialogVisible1.value = false
  }
}
const updateDuty = async () => {
  const res = await axios.post('/api/duty/update', dutyPeople.value)
  if (res.data.code === 0) {
    ElMessage.success('更新成功')
  } else {
    ElMessage.error('更新失败')
  }
}
const getStudentList = async () => {
  const res = await axios.post('/api/student/list/page', {
    ...searchValue.value,
    absentStatus:
      searchValue.value.absentStatus !== null ? searchValue.value.absentStatus : undefined,
    gender: searchValue.value.gender !== null ? searchValue.value.gender : undefined,
  })
  if (res.data.code === 0) {
    total.value = Number(res.data.data.total)
    absentList.value = res.data.data?.records
  } else {
    console.error('Failed to fetch data:', res.data.message)
  }
}
const getDutyVO = async (stId: number) => {
  const res = await axios.get('/api/duty/get/vo', {
    params: {
      stId: stId,
    },
  })
  if (res.data.code === 0) {
    dutyPeople.value = res.data.data
    console.log(res.data.data)
  }
}
const getOptionScoreTagType = (score: number) => (score > 60 ? 'success' : 'danger')
const getGenderTagType = (gender: number) => (gender === 0 ? 'primary' : 'danger')
const getAbsentStatusTagType = (status: number) => (status === 0 ? 'success' : 'danger')
const getAbsentStatusText = (status: number) => {
  if (status === 0) return '在校'
  if (status === 1) return '请假'
  return '未知状态'
}

const openDialog = async (student: StudentInfo) => {
  selectedStudent.value = student
  dialogVisible.value = true
}

const openAddStudentDialog = () => {
  drawer.value = true
  newStudent.value = { name: '', phone: '', gender: null }
}

const addStudent = async () => {
  try {
    const res = await axios.post('/api/student/add', newStudent.value)
    if (res.data.code === 0) {
      drawer.value = false
      getStudentList()
      await axios.post('/api/duty/add', {
        stId: res.data.data,
        taskName: '',
        taskTime: '',
        day: 0,
      })
      await axios.post('/api/situation/add', { stId: res.data.data })
      ElMessage.success('添加学生成功')


    } else {
      ElMessage.error('添加学生失败:', res.data.message)
    }
  } catch (error) {
    ElMessage.error('添加失败')
  }
}

const handlePageChange = (page: number) => {
  searchValue.value.current = page
  getStudentList()
}

const handleSizeChange = (size: number) => {
  searchValue.value.pageSize = size
  getStudentList()
}

const deleteStudent = async (studentId: number) => {
  try {
    const res = await axios.post('/api/student/delete', { id: studentId })

    if (res.data.code === 0) {
      await axios.post('/api/situation/delete', {
        stId: studentId,
      })
      await axios.post('/api/duty/delete', {stId: studentId})
      getStudentList() // 删除成功后刷新列表
      ElMessage.success('删除学生成功')

    } else {
      ElMessage.error('删除学生失败', res.data.message)
    }
  } catch (error) {
    console.error('Error deleting student:', error)
  }
}

onMounted(() => {
  getStudentList()
})
</script>

<style scoped lang="scss">
.studentAdmin {
  padding-top: 20px;

  .search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .el-input,
    .el-select {
      margin-right: 10px;
    }

    .el-button {
      margin-left: auto;
    }
  }

  .drawer-content {
    display: flex;
    flex-direction: column;
    gap: 10px; // Add space between inputs

    .drawer-input {
      margin-bottom: 10px;
    }
  }
}
</style>
